"""笔记分享模块的序列化器

定义笔记分享相关的数据序列化器，用于API数据的序列化和反序列化。
"""

from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import SharedNote, SharedFolder, ShareComment, ShareAccess, CommentLike, SharePermission
from apps.notes.serializers import NoteDetailSerializer, CategorySerializer

User = get_user_model()


class SharedFolderSerializer(serializers.ModelSerializer):
    """共享文件夹序列化器
    
    用于序列化共享文件夹信息。
    """
    
    category_detail = CategorySerializer(source='category', read_only=True)
    shared_by_info = serializers.SerializerMethodField()
    share_url = serializers.CharField(read_only=True)
    can_access = serializers.BooleanField(read_only=True)
    is_expired = serializers.BooleanField(read_only=True)
    is_view_limit_reached = serializers.BooleanField(read_only=True)
    
    class Meta:
        model = SharedFolder
        fields = [
            'id', 'category', 'category_detail', 'shared_by', 'shared_by_info',
            'share_token', 'title', 'description', 'permission', 'scope',
            'password', 'max_views', 'expires_at', 'is_active',
            'view_count', 'unique_visitors', 'share_url', 'can_access',
            'is_expired', 'is_view_limit_reached', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'shared_by', 'share_token', 'view_count', 'unique_visitors',
            'created_at', 'updated_at'
        ]
        extra_kwargs = {
            'password': {'write_only': True}
        }
    
    def get_shared_by_info(self, obj):
        """获取分享者信息"""
        return {
            'id': obj.shared_by.id,
            'email': obj.shared_by.email,
            'username': getattr(obj.shared_by, 'username', obj.shared_by.email)
        }
    
    def create(self, validated_data):
        """创建共享文件夹"""
        validated_data['shared_by'] = self.context['request'].user
        return super().create(validated_data)


class SharedFolderCreateSerializer(serializers.ModelSerializer):
    """创建共享文件夹序列化器
    
    用于创建共享文件夹的简化序列化器。
    """
    
    class Meta:
        model = SharedFolder
        fields = [
            'category', 'title', 'description', 'permission', 'scope',
            'password', 'max_views', 'expires_at'
        ]
    
    def create(self, validated_data):
        """创建共享文件夹"""
        validated_data['shared_by'] = self.context['request'].user
        return super().create(validated_data)


class SharedFolderAccessSerializer(serializers.Serializer):
    """访问共享文件夹序列化器
    
    用于验证访问共享文件夹的请求。
    """
    
    password = serializers.CharField(
        required=False,
        allow_blank=True,
        help_text='访问密码（如果需要）'
    )
    
    def validate(self, attrs):
        """验证访问权限"""
        shared_folder = self.context.get('shared_folder')
        if not shared_folder:
            raise serializers.ValidationError('共享文件夹不存在')
        
        if not shared_folder.can_access():
            raise serializers.ValidationError('共享文件夹不可访问')
        
        if shared_folder.password and attrs.get('password') != shared_folder.password:
            raise serializers.ValidationError('密码错误')
        
        return attrs


class SharedNoteSerializer(serializers.ModelSerializer):
    """分享笔记序列化器
    
    用于序列化分享笔记信息。
    """
    
    note_detail = NoteDetailSerializer(source='note', read_only=True)
    shared_by_info = serializers.SerializerMethodField()
    share_url = serializers.CharField(read_only=True)
    is_accessible = serializers.BooleanField(read_only=True)
    
    class Meta:
        model = SharedNote
        fields = [
            'id', 'note', 'note_detail', 'shared_by', 'shared_by_info',
            'share_token', 'share_url', 'scope', 'password',
            'expires_at', 'max_access_count', 'access_count',
            'allow_comments', 'allow_download', 'is_active',
            'is_accessible', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'shared_by', 'share_token', 'access_count',
            'created_at', 'updated_at'
        ]
        extra_kwargs = {
            'password': {'write_only': True}
        }
    
    def get_shared_by_info(self, obj):
        """获取分享者信息"""
        return {
            'id': obj.shared_by.id,
            'username': obj.shared_by.username,
            'first_name': obj.shared_by.first_name,
            'last_name': obj.shared_by.last_name
        }
    
    def validate(self, attrs):
        """验证数据"""
        # 如果设置了密码保护，scope不能是public
        if attrs.get('password') and attrs.get('scope') == 'public':
            raise serializers.ValidationError({
                'scope': '设置密码保护时不能选择公开分享'
            })
        
        # 如果设置了访问次数限制，必须大于0
        max_access = attrs.get('max_access_count')
        if max_access is not None and max_access <= 0:
            raise serializers.ValidationError({
                'max_access_count': '最大访问次数必须大于0'
            })
        
        return attrs


class ShareCommentSerializer(serializers.ModelSerializer):
    """分享评论序列化器
    
    用于序列化分享评论信息。
    """
    
    author_info = serializers.SerializerMethodField()
    likes_count = serializers.SerializerMethodField()
    is_liked = serializers.SerializerMethodField()
    replies = serializers.SerializerMethodField()
    
    class Meta:
        model = ShareComment
        fields = [
            'id', 'shared_note', 'author', 'author_info',
            'content', 'parent', 'likes_count', 'is_liked',
            'replies', 'is_approved', 'created_at', 'updated_at'
        ]
        read_only_fields = [
            'id', 'author', 'is_approved', 'created_at', 'updated_at'
        ]
    
    def get_author_info(self, obj):
        """获取评论者信息"""
        return {
            'id': obj.author.id,
            'username': obj.author.username,
            'first_name': obj.author.first_name,
            'last_name': obj.author.last_name
        }
    
    def get_likes_count(self, obj):
        """获取点赞数"""
        return obj.likes.count()
    
    def get_is_liked(self, obj):
        """获取当前用户是否点赞"""
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.likes.filter(user=request.user).exists()
        return False
    
    def get_replies(self, obj):
        """获取回复评论"""
        if obj.parent is None:  # 只有顶级评论才显示回复
            replies = obj.replies.filter(
                is_approved=True, is_deleted=False
            ).order_by('created_at')
            return ShareCommentSerializer(
                replies, many=True, context=self.context
            ).data
        return []


class ShareAccessSerializer(serializers.ModelSerializer):
    """分享访问记录序列化器
    
    用于序列化分享访问记录信息。
    """
    
    visitor_info = serializers.SerializerMethodField()
    shared_note_info = serializers.SerializerMethodField()
    
    class Meta:
        model = ShareAccess
        fields = [
            'id', 'shared_note', 'shared_note_info', 'visitor',
            'visitor_info', 'ip_address', 'user_agent',
            'accessed_at'
        ]
        read_only_fields = ['id', 'accessed_at']
    
    def get_visitor_info(self, obj):
        """获取访问者信息"""
        if obj.visitor:
            return {
                'id': obj.visitor.id,
                'username': obj.visitor.username,
                'first_name': obj.visitor.first_name,
                'last_name': obj.visitor.last_name
            }
        return None
    
    def get_shared_note_info(self, obj):
        """获取分享笔记信息"""
        return {
            'id': obj.shared_note.id,
            'note_title': obj.shared_note.note.title,
            'share_token': obj.shared_note.share_token
        }


class CommentLikeSerializer(serializers.ModelSerializer):
    """评论点赞序列化器
    
    用于序列化评论点赞信息。
    """
    
    class Meta:
        model = CommentLike
        fields = ['id', 'comment', 'user', 'created_at']
        read_only_fields = ['id', 'created_at']


class SharePermissionSerializer(serializers.ModelSerializer):
    """分享权限序列化器
    
    用于序列化分享权限信息。
    """
    
    user_info = serializers.SerializerMethodField()
    
    class Meta:
        model = SharePermission
        fields = [
            'id', 'shared_note', 'user', 'user_info',
            'permission_type', 'granted_at'
        ]
        read_only_fields = ['id', 'granted_at']
    
    def get_user_info(self, obj):
        """获取用户信息"""
        return {
            'id': obj.user.id,
            'username': obj.user.username,
            'email': obj.user.email,
            'first_name': obj.user.first_name,
            'last_name': obj.user.last_name
        }